//
//  StudyVideoDetailVC.m
//  students
//
//  Created by 任辰东 on 2024/2/23.
//

#import "StudyVideoDetailVC.h"
//#import "StudyApis.h"
#import "NSString+timeStamp.h"
//#import "StudyDetailModel.h"
#import <SJVideoPlayer/SJVideoPlayer.h>
#import <SJUIKit/NSAttributedString+SJMake.h>
#import "RCDAvatarWithMaskControl.h"
#import "NSString+timeStamp.h"
#import "WMMenuView.h"

@interface StudyVideoDetailVC ()<WMMenuViewDelegate,WMMenuViewDataSource>
@property (nonatomic, strong) UIView *topBgView;
@property (nonatomic, strong) SJVideoPlayer *player;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIView *userInfoView;
@property (nonatomic, strong) UIView *line;
@property (nonatomic, strong) RCDAvatarWithMaskControl *avatarView;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *timeLabel;

@property (nonatomic, strong) WMMenuView *rateView;
@property (nonatomic, strong) NSArray *menuDataArray;

@property (nonatomic, strong) NSTimer *countDownTimer;
@property (nonatomic, strong) UIButton *countDownBtn;
@property (nonatomic , strong) StudyModel *model;

@property (nonatomic, assign) long totalTime;
@property (nonatomic, assign) NSInteger index;

@property (nonatomic, assign) float screenWidth;
@property (nonatomic, assign) float screenHeight;

@end

@implementation StudyVideoDetailVC

-(instancetype)initWithModel:(StudyModel *)model
{
    self = [super init];
    if (self) {
        _model = model;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"详情";
    
//    [self getData];

    [self setupPalyer];
    
    self.index = 1;
    self.screenWidth = kScreenWidth;
    self.screenHeight = kScreenHeight;
    
    // 转屏通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didChangeRotate:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
    
    NSURL *videoUrl = [NSURL URLWithString:self.model.video_url];
    // 设置资源进行播放
    SJVideoPlayerURLAsset *asset = [[SJVideoPlayerURLAsset alloc] initWithURL:videoUrl];
    _player.URLAsset = asset;
    NSURL *imageUrl = [NSURL URLWithString:self.model.cover_url];
    [_player.presentView.placeholderImageView sd_setImageWithURL:imageUrl ];

    self.titleLabel.text = self.model.title;
    self.nameLabel.text = self.model.user_name;
    self.timeLabel.text = [self.model.create_time dateStringWithFormat:@"yyyy-MM-dd"];
    self.avatarView.avatarUrl = self.model.headimg;
    
    
//    WeakSelf
//    [self.player.playbackObserver setTimeControlStatusDidChangeExeBlock:^(__kindof SJBaseVideoPlayer * _Nonnull player) {
//        StrongSelf
//        if (!self.model.status.boolValue && self.countDownTimer) {
//
//            if (player.timeControlStatus == SJPlaybackTimeControlStatusPaused) {
//                
//                [self.countDownTimer setFireDate:[NSDate distantFuture]];
//                
//            }else if (player.timeControlStatus == SJPlaybackTimeControlStatusPlaying){
//                
//                [self.countDownTimer setFireDate:[NSDate distantPast]];
//                
//            }
//        }
//    }];
    
}

- (void)getData
{
//    NSDictionary *params = @{
//        @"user_id":[GVUserDefaults standardUserDefaults].uid,
//        @"article_id":self.model.article_id
//    };
//    WeakSelf
//    [self showLoadingHUDWithMessage:nil];
//    [StudyApis xxXuexiDetatilRequestWithParams:params SuccessBlock:^(NSNumber *code, NSString *msg, id responseData) {
//        StrongSelf
//        [self hideLoadingHUD];
//        StudyDetailModel *model = [StudyDetailModel mj_objectWithKeyValues:responseData];
//        NSURL *videoUrl = [NSURL URLWithString:model.video_url];
//        // 设置资源进行播放
//        SJVideoPlayerURLAsset *asset = [[SJVideoPlayerURLAsset alloc] initWithURL:videoUrl];
//        _player.URLAsset = asset;
//        NSURL *imageUrl = [NSURL URLWithString:model.cover_url];
//        [_player.presentView.placeholderImageView sd_setImageWithURL:imageUrl ];
//        
//        self.titleLabel.text = model.title;
//        self.nameLabel.text = model.organ_name;
//        self.timeLabel.text = [model.create_time dateStringWithFormat:@"yyyy-MM-dd"];
//        self.avatarView.avatarUrl = model.headimg;
//        
//        if (!self.model.status.boolValue) {
//            self.totalTime = model.study_time.longLongValue;
//            [self setupCountDownBtn];
//            self.countDownBtn.hidden = NO;
//            self.countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1
//                                                                  target:self
//                                                                selector:@selector(timeRefresh:)
//                                                                userInfo:nil
//                                                                 repeats:YES];
//            [[NSRunLoop currentRunLoop] addTimer:self.countDownTimer forMode:NSRunLoopCommonModes];
//        }else{
//            self.countDownBtn.hidden = YES;
//        }
//            
//    } FailureBlock:^(NSNumber *code, NSString *msg) {
//        StrongSelf
//        [self showWarningHUDWithMessage:msg completion:NULL];
//    }];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    kAppDelegate.allowRotation = YES;
//    self.navigationController.navigationBar.hidden = YES;
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [_player vc_viewDidAppear];
}

- (void)viewWillDisappear:(BOOL)animated
{
//    [self invalidateTimer];
    [super viewWillDisappear:animated];
//    kAppDelegate.allowRotation = NO;
    [_player vc_viewWillDisappear];
//    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [_player vc_viewDidDisappear];
}


#pragma mark -- private

-(void)invalidateTimer
{
    if(self.countDownTimer)
    {
        [self.countDownTimer invalidate];
        self.countDownTimer = nil;
    }
}

- (void)timeRefresh:(NSTimer *)timer
{
    self.totalTime--;
    [self setupCountDownBtn];
    
    if (self.totalTime<=0) {
        [self invalidateTimer];
        [self endStudy];
    }
}

- (void)endStudy
{
//    NSDictionary *params = @{
//        @"user_id":[GVUserDefaults standardUserDefaults].uid,
//        @"article_id":self.model.article_id
//    };
//    WeakSelf
//    [StudyApis xxStudyAddRequestWithParams:params SuccessBlock:^(NSNumber *code, NSString *msg, id responseData) {
//        StrongSelf
//        self.countDownBtn.hidden = YES;
//        [self showCompletionHUDWithMessage:msg completion:NULL];
//        self.model.status = @"1";
//        if (self.successBlcok) {
//            self.successBlcok(self.model);
//        }
//            
//    } FailureBlock:^(NSNumber *code, NSString *msg) {
//        StrongSelf
//        [self showWarningHUDWithMessage:msg completion:NULL];
//    }];
}

-(void)setupCountDownBtn
{
    if (self.totalTime > 3600) {
        NSString *hour = [NSString stringWithFormat:@"%02ld",self.totalTime/3600];
        NSString *minutes = [NSString stringWithFormat:@"%02ld",(self.totalTime%3600)/60];
        NSString *second = [NSString stringWithFormat:@"%02ld",self.totalTime%60];
        [self.countDownBtn setTitle:[NSString stringWithFormat:@"%@:%@:%@",hour,minutes,second] forState:UIControlStateNormal];
    }else{
        NSString *minutes = [NSString stringWithFormat:@"%02ld",self.totalTime/60];
        NSString *second = [NSString stringWithFormat:@"%02ld",self.totalTime%60];
        [self.countDownBtn setTitle:[NSString stringWithFormat:@"%@:%@",minutes,second] forState:UIControlStateNormal];
    }
}

- (void)setupPalyer
{
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    SJVideoPlayer.update(^(SJVideoPlayerConfigurations * _Nonnull configs) {
    
        configs.resources.backImage = UIImageWithName(@"back_white");
    });

    SJVideoPlayer.updateResources(^(id<SJVideoPlayerControlLayerResources>  _Nonnull resources) {
        resources.progressThumbSize = 8;
        resources.progressThumbColor = [UIColor whiteColor];
        resources.progressTraceColor = [UIColor redColor];
        resources.progressBufferColor = [UIColor whiteColor];
        resources.smallScreenImage = UIImageWithName(@"btn_zoom_in");
        resources.fullscreenImage = UIImageWithName(@"btn_zoom_out");
        resources.playImage = UIImageWithName(@"video_play");
        resources.pauseImage = UIImageWithName(@"video_pause");
    });
    
//    [self.player.defaultEdgeControlLayer.bottomAdapter exchangeItemForTag:SJEdgeControlLayerBottomItem_DurationTime withItemForTag:SJEdgeControlLayerBottomItem_Progress];
//    [self.player.defaultEdgeControlLayer.bottomAdapter removeItemForTag:SJEdgeControlLayerBottomItem_Separator];
//    [self.player.defaultEdgeControlLayer.bottomAdapter reload];
//
//    [self.player.defaultEdgeControlLayer.topAdapter removeItemForTag:SJEdgeControlLayerBottomItem_Full];
//    [self.player.defaultEdgeControlLayer.topAdapter reload];
    
    self.player.defaultEdgeControlLayer.leftMargin = 16;
    self.player.defaultEdgeControlLayer.rightMargin = 16;
    self.player.gestureController.supportedGestureTypes = SJPlayerGestureTypeMask_SingleTap;
    SJEdgeControlButtonItem *titleItem = [_player.defaultEdgeControlLayer.bottomAdapter itemForTag:SJEdgeControlLayerBottomItem_Progress];
    titleItem.alpha = 0;
    [titleItem removeAllActions];
    titleItem.hidden = YES;
//    titleItem.insets =  SJEdgeInsetsMake(200, 16);
    [_player.defaultEdgeControlLayer.bottomAdapter reload];
    self.player.defaultEdgeControlLayer.bottomAdapter.backgroundColor = UIColorFromHexWithAlpha(0x000000, 0.5);
    self.player.defaultEdgeControlLayer.bottomHeight = 44.0;
    self.player.resumePlaybackWhenPlayerHasFinishedSeeking = YES;
    
    // 为快进按钮提供一个标识tag(tag需要是唯一的, 后续在需要时, 可用于获取该item)
    SJEdgeControlButtonItemTag rateItemTag = 100000;
    // 创建快进按
    NSAttributedString *title = [[NSAttributedString alloc]initWithString:@"1.0X" attributes:@{NSForegroundColorAttributeName:UIColorFromHex(kColorWhite), NSFontAttributeName:UIFontSize(14)}];
    
    SJEdgeControlButtonItem *rateItem = [[SJEdgeControlButtonItem alloc]initWithTitle:title target:self action:@selector(shareItemWasTapped) tag:rateItemTag];
    // 添加到 topAdapter 中
    [_player.defaultEdgeControlLayer.bottomAdapter addItem:rateItem];
    
    [self.player.defaultEdgeControlLayer.bottomAdapter exchangeItemForTag:SJEdgeControlLayerBottomItem_Full withItemForTag:rateItemTag];

    [self.player.defaultEdgeControlLayer.bottomAdapter reload];

}

 -(void)shareItemWasTapped
{
    self.rateView = [[WMMenuView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
    self.rateView.delegate = self;
    self.rateView.dataSource = self;
    self.rateView.style = WMMenuViewStyleLine;
    self.rateView.layoutMode = WMMenuViewLayoutModeScatter;
    self.rateView.backgroundColor = UIColorFromHexWithAlpha(0x000000, 1);

    [self.rateView selectItemAtIndex:self.index];
    // 添加自定义视图到底部容器视图中
    [self.player.defaultEdgeControlLayer.bottomContainerView addSubview:self.rateView];

    [self.rateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        make.height.offset(44);
    }];
}


- (void)didChangeRotate:(NSNotification*)notice {
    
    if (self.avatarView) {
        [self.rateView removeFromSuperview];
    }
}
- (BOOL)shouldAutorotate {
    return NO;
}

- (BOOL)prefersHomeIndicatorAutoHidden {
    return YES;
}

#pragma mark -- WMMenuViewDataSource

- (NSInteger)numbersOfTitlesInMenuView:(WMMenuView *)menu
{
    return self.menuDataArray.count;
}

- (NSString *)menuView:(WMMenuView *)menu titleAtIndex:(NSInteger)index
{
    return self.menuDataArray[index];
}

#pragma mark -- WMMenuViewDelegate

- (UIColor *)menuView:(WMMenuView *)menu titleColorForState:(WMMenuItemState)state atIndex:(NSInteger)index
{
    return UIColorFromHex(kColorWhite);
}

- (void)menuView:(WMMenuView *)menu didSelesctedIndex:(NSInteger)index currentIndex:(NSInteger)currentIndex
{
    self.index = index;
    NSString *rate = self.menuDataArray[index];

    NSAttributedString *title = [[NSAttributedString alloc]initWithString:rate attributes:@{NSForegroundColorAttributeName:UIColorFromHex(kColorWhite), NSFontAttributeName:UIFontSize(14)}];
    SJEdgeControlButtonItem *rateItem = [self.player.defaultEdgeControlLayer.bottomAdapter itemForTag:100000];
    rateItem.title = title;
    self.player.rate = [rate stringByReplacingOccurrencesOfString:@"X" withString:@""].floatValue;
    [self.player.defaultEdgeControlLayer.bottomAdapter reload];
    [self.rateView removeFromSuperview];
    
}

//- (CGFloat)menuView:(WMMenuView *)menu itemMarginAtIndex:(NSInteger)index
//{
//    return 20;
//}

- (CGFloat)menuView:(WMMenuView *)menu titleSizeForState:(WMMenuItemState)state atIndex:(NSInteger)index
{
    return FitFontSize(15);
}

//- (CGFloat)menuView:(WMMenuView *)menu widthForItemAtIndex:(NSInteger)index
//{
//    NSDictionary *dic = @{NSFontAttributeName:UIFontSize(15)};  //指定字号
//    CGRect rect = [self.menuDataArray[index] boundingRectWithSize:CGSizeMake(0, 30)/*计算宽度时要确定高度*/ options:NSStringDrawingUsesLineFragmentOrigin |
//                   NSStringDrawingUsesFontLeading attributes:dic context:nil];
//    return rect.size.width;
//}


#pragma mark -- setupUI

-(void)setupViews
{
    [self.view addSubview:self.topBgView];
    [self.topBgView addSubview:self.player.view];
    [self.view addSubview:self.userInfoView];
    [self.userInfoView addSubview:self.titleLabel];
    [self.userInfoView addSubview:self.line];
    [self.userInfoView addSubview:self.avatarView];
    [self.userInfoView addSubview:self.nameLabel];
    [self.userInfoView addSubview:self.timeLabel];
//    [self.view addSubview:self.countDownBtn];
}

-(void)setupLayout
{
    [self.topBgView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.left.right.equalTo(self.view);
//        make.height.mas_equalTo(kScreenWidth *9.0/16.0 + KStatusBarHeight);
        make.height.mas_equalTo(kScreenWidth *9.0/16.0);
    }];

    [self.player.view mas_makeConstraints:^(MASConstraintMaker *make) {

//        make.top.equalTo(self.topBgView).offset(KStatusBarHeight);
        make.top.equalTo(self.topBgView).offset(0);
        make.left.right.equalTo(self.topBgView);
        make.height.mas_equalTo(kScreenWidth *9.0/16.0);
    }];
    
    [self.userInfoView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.equalTo(self.topBgView.mas_bottom);
        make.left.right.equalTo(self.view);
    }];

    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.equalTo(self.userInfoView ).offset(15);
        make.left.equalTo(self.userInfoView ).offset(15);
        make.right.equalTo(self.userInfoView ).offset(-15);
    }];

    [self.line mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.equalTo(self.titleLabel.mas_bottom ).offset(15);
        make.left.equalTo(self.userInfoView ).offset(15);
        make.right.equalTo(self.userInfoView ).offset(-15);
        make.height.mas_equalTo(kOnePixel);
    }];


    [self.avatarView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.equalTo(self.line ).offset(15+5);
        make.left.equalTo(self.userInfoView ).offset(15);
        make.height.width.mas_equalTo(40);
        make.bottom.equalTo(self.userInfoView.mas_bottom).offset(-15);
    }];

    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.equalTo(self.avatarView.mas_top);
        make.left.equalTo(self.avatarView.mas_right).offset(10);
        make.right.equalTo(self.userInfoView).offset(-15);
    }];

    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {

        make.bottom.equalTo(self.avatarView.mas_bottom);
        make.left.equalTo(self.avatarView.mas_right).offset(10);
        make.right.equalTo(self.timeLabel.mas_right).offset(-10);
    }];
    
//    [self.countDownBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//       
//        make.bottom.equalTo(self.view).offset(kBottomOffset-80);
//        make.right.equalTo(self.view).offset(-30);
//        make.height.width.mas_equalTo(80);
//    }];
//    
//    self.countDownBtn.layer.cornerRadius = 40;
//    self.countDownBtn.layer.masksToBounds = YES;
}


#pragma mark -- lazyload

- (SJVideoPlayer *)player {
    if (!_player) {
        _player = [SJVideoPlayer lightweightPlayer];
        _player.automaticallyPerformRotationOrFitOnScreen = NO;
//        _player.defaultEdgeControlLayer.fixesBackItem = YES; // 返回按钮一直显示
        _player.defaultEdgeControlLayer.hiddenBackButtonWhenOrientationIsPortrait = YES;
        _player.defaultEdgeControlLayer.showsMoreItem = NO;
        _player.defaultEdgeControlLayer.hiddenBottomProgressIndicator = YES;
        if (@available(iOS 14.0, *)) {
            _player.defaultEdgeControlLayer.automaticallyShowsPictureInPictureItem = NO;
        } else {
            // Fallback on earlier versions
        }
    }
    return _player;
}

-(UIView *)topBgView
{
    if (!_topBgView) {
        _topBgView = [UIView new];
        _topBgView.backgroundColor = UIColorFromHex(0x000000);
    }
    return _topBgView;
}

-(UIView *)line
{
    if (!_line) {
        _line = [UIView new];
        _line.backgroundColor = UIColorFromHex(kColorLine);
    }
    return _line;
}

-(UIView *)userInfoView
{
    if (!_userInfoView) {
        _userInfoView = [UIView new];
        [_userInfoView addBottomLine];
        _userInfoView.backgroundColor = UIColorFromHex(0xffffff);
    }
    return _userInfoView;
}

-(RCDAvatarWithMaskControl *)avatarView
{
    if (!_avatarView) {
        _avatarView = [RCDAvatarWithMaskControl new];
    }
    return _avatarView;
}

-(UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [UILabel new];
        _titleLabel.textColor = UIColorFromHex(kColorBlack);
        _titleLabel.font = UIBoldFontSize(18);
        _titleLabel.numberOfLines = 0;
    }
    return _titleLabel;
}

-(UILabel *)nameLabel
{
    if (!_nameLabel) {
        _nameLabel = [UILabel new];
        _nameLabel.textColor = UIColorFromHex(kColorTitle);
        _nameLabel.font = UIFontSize(14);
    }
    return _nameLabel;
}

-(UILabel *)timeLabel
{
    if (!_timeLabel) {
        _timeLabel = [UILabel new];
        _timeLabel.textColor = UIColorFromHex(kColorSubTitle);
        _timeLabel.font = UIFontSize(12);
    }
    return _timeLabel;
}

-(UIButton *)countDownBtn
{
    if (!_countDownBtn) {
        _countDownBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_countDownBtn setBackgroundColor:[UIColor grayColor]];
        [_countDownBtn setTitle:@"00:00" forState:UIControlStateNormal];
        [_countDownBtn setTitleColor:UIColorFromHex(kColorWhite) forState:UIControlStateNormal];
    }
    return _countDownBtn;
}

//-(WMMenuView *)rateView
//{
//    if (!_rateView) {
//        _rateView = [[WMMenuView alloc]initWithFrame:CGRectMake(0, 0,kScreenWidth, 44)];
//        _rateView.delegate = self;
//        _rateView.dataSource = self;
//        _rateView.style = WMMenuViewStyleLine;
//        _rateView.layoutMode = WMMenuViewLayoutModeScatter;
//        _rateView.backgroundColor = UIColorFromHexWithAlpha(0x000000, 1);
//        [_rateView addBottomLine];
//    }
//    return _rateView;
//}

-(NSArray *)menuDataArray
{
    if (!_menuDataArray) {
        _menuDataArray = @[@"0.5X",@"1.0X",@"1.25X",@"1.5X",@"2X"];
    }
    return _menuDataArray;
}

@end
